package com.example.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.base.handler.Exception.GuliException;
import com.example.edu.entity.Subject;
import com.example.edu.entity.excel.SubjectData;
import com.example.edu.entity.subject.OneSubject;
import com.example.edu.entity.subject.TwoSubject;
import com.example.edu.listener.SubjectEventListener;
import com.example.edu.mapper.SubjectMapper;
import com.example.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author 李泽伟
 * @since 2022-05-27
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void importSubjectData(MultipartFile file, SubjectService subjectService) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class,new SubjectEventListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new GuliException(20002,"添加课程分类失败");
        }

    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //1.获取所有一级分类
        QueryWrapper oneWrapper=new QueryWrapper();
        oneWrapper.eq("parent_id","0");
        List<Subject> oneSubjects=baseMapper.selectList(oneWrapper);
        //2.获取所有二级分类
        QueryWrapper twoWrapper=new QueryWrapper();
        twoWrapper.ne("parent_id","0");
        List<Subject> twoSubjects=baseMapper.selectList(twoWrapper);
        //3.循环封装一级分类
        List<OneSubject> finalOneSubjects=new ArrayList<>();
        for (Subject oneItem : oneSubjects) {
            OneSubject oneSubject=new OneSubject();
            BeanUtils.copyProperties(oneItem,oneSubject);
            String id = oneItem.getId();
            //4.循环遍历封装所有二级分类
            List<TwoSubject> finalTwoSubjects=new ArrayList<>();
            for (Subject twoItem : twoSubjects) {
                if(twoItem.getParentId().equals(id)){
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(twoItem,twoSubject);
                    finalTwoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(finalTwoSubjects);
            finalOneSubjects.add(oneSubject);
        }
        return finalOneSubjects;
    }
}
